package com.lily.aidouzixun.util;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.lily.aidouzixun.datacenter.RemoteServer;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Properties;
import java.util.TreeSet;

public class MyCrashHandler implements UncaughtExceptionHandler {
    /** Debug Log tag */
    public static final String TAG = "MyCrashHandler";

    /** 系统默认的UncaughtException处理类 */
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    /** CrashHandler实例 */
    private static volatile MyCrashHandler INSTANCE;
    /** 程序的Context对象 */
    private Context mContext;
    /** 使用Properties来保存设备的信息和错误堆栈信息 */
    private Properties mDeviceCrashInfo = new Properties();
    private static final String VERSION_NAME = "versionName";
    private static final String VERSION_CODE = "versionCode";
    private static final String STACK_TRACE = "STACK_TRACE";
    /** 错误报告文件的扩展名 */
    private static final String CRASH_REPORTER_EXTENSION = ".cr";
    /** 保证只有一个CrashHandler实例 */
	private String msg;

    private MyCrashHandler() {
    }

    /** 获取CrashHandler实例 ,单例模式 */
    public static MyCrashHandler getInstance() {
        if (INSTANCE == null) {
            synchronized(MyCrashHandler.class) {
                if (INSTANCE == null)
                    INSTANCE = new MyCrashHandler();
            }
        }
        return INSTANCE;
    }

    /**
     * 初始化,注册Context对象, 获取系统默认的UncaughtException处理器, 设置该CrashHandler为程序的默认处理器
     *
     * @param ctx
     */
    public void init(Context ctx) {
        mContext = ctx;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            // Sleep一会后结束程序
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                if(MyConstant.DEBUG)
                    Log.e(TAG, "Error : ", e);
            }
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(10);
        }
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 开发者可以根据自己的情况来自定义异常处理逻辑
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return true;
        }

        // 收集设备信息
        collectCrashDeviceInfo(mContext);
        // 保存错误报告文件
        saveCrashInfoToFile(ex);

        // 使用Toast来显示异常信息
		new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				if (msg != null && msg.contains("java.lang.OutOfMemoryError"))
					Toast.makeText(mContext, "警告！当前系统可用内存不足...",
                            Toast.LENGTH_SHORT).show();
				else
					Toast.makeText(mContext, "对不起，程序异常，请与我们联系...",
							Toast.LENGTH_SHORT).show();
				Looper.loop();
			}
		}.start();

        return true;
    }

    /**
     * 在程序启动时候, 可以调用该函数来发送以前没有发送的报告
     */
    public void sendPreviousReportsToServer() {
        sendCrashReportsToServer(mContext);
    }

    /**
     * 把错误报告发送给服务器,包含新产生的和以前没发送的.
     *
     * @param ctx
     */
    private void sendCrashReportsToServer(Context ctx) {
        L.i(TAG, "sendCrashReportsToServer start!");
        String[] crFiles = getCrashReportFiles(ctx);
        if (crFiles != null && crFiles.length > 0) {
            TreeSet<String> sortedFiles = new TreeSet<String>();
            sortedFiles.addAll(Arrays.asList(crFiles));
            for (String fileName : sortedFiles) {
                File cr = new File(ctx.getFilesDir(), fileName);
                postReport(cr);
            }
        } else {
            L.i(TAG, "crash log is null!");
        }
        L.i(TAG, "sendCrashReportsToServer end!");
    }

    private void postReport(File file) {
        L.i(TAG, "postReport start!");
        try {
            byte[] buffer = new byte[4096];
            int count = 0;

            FileInputStream fin = new FileInputStream(file);
            final ByteArrayOutputStream stream = new ByteArrayOutputStream();
            while ((count = fin.read(buffer)) > 0) {
                stream.write(buffer, 0, count);
            }
            fin.close();

            String log = stream.toString();
            stream.close();
            file.delete();// 删除已发送的报告
            //todo 发送crashLog给服务器
            RemoteServer.commitCrashLog(mContext, log.replace("\\n\\t", "\n").replace("\\", ""));
            buffer = null;
            log = null;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        L.i(TAG, "postReport end!");
    }

    /**
     * 获取错误报告文件名
     * @param ctx
     * @return
     */
    private String[] getCrashReportFiles(Context ctx) {
        L.i(TAG, "getCrashReportFiles start!");
        File filesDir = ctx.getFilesDir();
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.endsWith(CRASH_REPORTER_EXTENSION);
            }
        };
        L.i(TAG, "getCrashReportFiles end!");
        return filesDir.list(filter);
    }

    /**
     * 保存错误信息到文件中
     *
     * @param ex
     * @return
     */
    private String saveCrashInfoToFile(Throwable ex) {
        L.i(TAG, "saveCrashInfoToFile start!");
        Writer info = new StringWriter();
        PrintWriter printWriter = new PrintWriter(info);
        ex.printStackTrace(printWriter);

        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }

        msg = info.toString();
        printWriter.close();

        L.e(TAG, "crash log: " + msg);
        /*if (msg.contains("com.wochacha.StartupActivity")) {
            WccConfigure.setStartupUIShow(mContext, false);
        }*/

        String newMD5 = DataConverter.getMD5(msg.getBytes());
        for (int i=0; i<10; i++) {
            String oldMD5 = MyConfig.getCrashLogMD5(mContext, i);
            if (newMD5.equals(oldMD5)) return msg;
        }

        int oldMD5Index = MyConfig.getCrashLogIndex(mContext);
        MyConfig.setCrashLogMD5(mContext, oldMD5Index, newMD5);
        if (oldMD5Index == 9)
            oldMD5Index = 0;
        MyConfig.setCrashLogIndex(mContext, oldMD5Index + 1);

        mDeviceCrashInfo.put(STACK_TRACE, msg);

        try {
            long timestamp = System.currentTimeMillis();
            String fileName = "crash-" + timestamp + CRASH_REPORTER_EXTENSION;
            L.i(TAG, "crash log path:" + fileName);
            FileOutputStream trace = mContext.openFileOutput(fileName, Context.MODE_PRIVATE);
            mDeviceCrashInfo.store(trace, "");
            trace.flush();
            trace.close();
            L.i(TAG, "saveCrashInfoToFile end!");
            return msg;
        } catch (Exception e) {
            if (MyConstant.DEBUG)
                Log.e(TAG, "an error occured while writing report file...", e);
        }
        return msg;
    }

    /**
     * 收集程序崩溃的设备信息
     *
     * @param ctx
     */
    private void collectCrashDeviceInfo(Context ctx) {
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                mDeviceCrashInfo.put(VERSION_NAME, pi.versionName == null ? "not set" : pi.versionName);
                mDeviceCrashInfo.put(VERSION_CODE, pi.versionCode + "");
            }
        } catch (NameNotFoundException e) {
            if (MyConstant.DEBUG)
                Log.e(TAG, "Error while collect package info", e);
        }
        // 使用反射来收集设备信息.在Build类中包含各种设备信息,
        // 例如: 系统版本号,设备生产商 等帮助调试程序的有用信息
        // 具体信息请参考后面的截图
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                mDeviceCrashInfo.put(field.getName(), field.get(null) + "");
                if (MyConstant.DEBUG)
                    Log.d(TAG, field.getName() + " : " + field.get(null));

            } catch (Exception e) {
                if (MyConstant.DEBUG)
                    Log.e(TAG, "Error while collect crash info", e);
            }
        }
    }
}
